package com.yequan.leetcode.algorithm.search.BinarySearch.findIndex;

/**
 * @author : Administrator
 * @date : 2020/4/5
 */
public class FindIndex {

    public static void main(String[] args) {
        int[] nums1 = {5, 6, 7, 0, 1, 2, 3};
        int[] nums2 = {4, 5, 6, 7, 0};
        int[] nums3 = {1, 2, 3, 4, 5};
        FindIndex findIndex = new FindIndex();
        System.out.println(findIndex.findIndex(nums2));
    }

    /**
     * 二分法查找旋转点
     *
     * @param nums
     * @return
     */
    public int findIndex(int[] nums) {
        int left = 0;
        int right = nums.length - 1;
        if (nums[right] > nums[0]) {
            return 0;
        }
        while (left <= right) {
            int mid = left + ((right - left) >> 1);
            //往后探测一位
            if (nums[mid] > nums[mid + 1]) {
                return mid;
            }
            //往前探测一位
            if (nums[mid - 1] > nums[mid]) {
                return mid - 1;
            }
            //这里只需要比较一次,因为只需要确定前半段是否有序,如果有序,则肯定在mid以后的位置发生旋转
            if (nums[mid] > nums[0]) {
                left = mid + 1;
            } else {
                //所处位置为无序或包含旋转位置的半段,所以以后每次去检测这半段就行了
                right = mid - 1;
            }
        }
        return -1;
    }

}
